<template>
  <div
    class="m-upload-file"
    v-loading="downloadLoading"
    :element-loading-text="loadingText"
  >
    <el-upload
      class="upload-form"
      drag
      :data="data"
      :headers="headers"
      :auto-upload="false"
      ref="upload"
      :on-success="onSuccess"
      :on-change="onChange"
      :on-remove="onRemove"
      :on-error="onError"
      :before-upload="beforeUpload"
      :action="action"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="tipText"> 请使用下载模板填写数据导入 </div>
    </el-upload>
    <div class="upload-button-layout">
      <el-button
        :loading="submitLoading"
        class="mb-sm btn btn-primary"
        size="small"
        type="primary"
        @click="submitForm"
      >导入</el-button>
      <el-button
        style="margin-right:5px"
        class="mb-sm btn btn-primary btn-outline"
        type="primary"
        plain
        @click="close"
      >取消</el-button>
      <!-- <template v-if="!supportTxt">
        <el-button
          style="margin-right:5px"
          class="mb-sm btn btn-primary btn-outline"
          @click="getTplUrl"
        >下载模板</el-button>
      </template> -->
    </div>
    <a
      style="display:none"
      ref="downloadTpl"
      :download="tplName"
      :href="tplHref"
    ></a>
    <a
      style="display:none"
      :href="href"
      download
      ref="download"
    ></a>
  </div>
</template>


<script>

import request from '@/utils/request'
const prefix = process.env.VUE_APP_BASE_API

export default {
  name: 'CubeUpload',
  props: {
    data: {
      type: Object,
      default: () => { }
    },
    actionUrl: {
      type: String,
      required: true,
      default: () => ''
    },
    tplUrl: {
      type: String,
      required: true,
      default: () => ''
    },
    tplName: {
      type: String,
      default: () => '导入模板.xls'
    },
    async: {
      type: Boolean,
      default: () => false
    },
    supportTxt: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      headers: null,
      submitLoading: false,
      downloadLoading: false,
      fileList: [],
      href: '',
      tplHref: '',
      count: 0,
      loadingText: '',
    }
  },
  created() {
    this.headers = {
      token: this.$store.getters.token
    }
  },
  computed: {
    action() {
      return `${prefix}${this.actionUrl}`
    }
  },
  methods: {
    getTplUrl(evt) {
      if (this.tplHref) {
        if (evt) {
          this.$refs.downloadTpl.click();
        }
        return
      }
      const params = {}
      request({ url: this.tplUrl, method: 'GET', params }).then(({ data }) => {
        const { success } = data
        if (success) {
          const url = `${prefix}${data.data}`
          this.tplHref = url
          this.download(url)
        }
      }).catch(e => {
        this.loading = false
        console.log(e)
      })
    },
    submitForm() {
      if (!this.fileList.length) {
        this.$message({
          message: '请添加导入文件',
          type: 'warning'
        });
      }
      this.$refs.upload.submit()
    },
    close() {
      this.$emit('close')
    },
    onSuccess({ data, message }, file, fileList) {
      const { response } = file
      this.submitLoading = false
      if (this.async) {
        // console.log('异步上传。系统后台不规划,前端保留');
      } else {
        this.dealResultOnUp(response)
      }

    },
    dealResultOnUp(response = {}) {
      const { success, msg } = response
      if (success) {
        this.$message({
          type: 'success',
          message: '数据导入成功!'
        });
        this.close()
      } else {
        this.$refs.upload.clearFiles()
        this.fileList = []
        this.$message({
          duration: 0,
          showClose: true,
          message: `${msg}`,
          type: 'warning'
        });
      }
    },
    dealResult(flag, href) {
      this.href = href;
      if (flag) {
        this.$emit('success')
        this.$confirm('导入成功', {
          type: 'success',
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.close()
        }).catch(() => {
          if (this.$refs.upload) {
            this.$refs.upload.clearFiles()
          }
          this.fileList = []
        })
      } else {
        this.$confirm('存在失败记录，请下载处理结果，查看详细信息', '提示', {
          type: 'error',
          confirmButtonText: '下载',
          cancelButtonText: '取消'
        }).then(() => {
          this.download(href)
        }).catch(() => {

        })
        this.$refs.upload.clearFiles()
        this.fileList = []
      }
    },
    download(href) {
      let a = document.createElement('a')
      a.href = href || this.href
      a.style.display = 'none'
      // a.download = true
      a.download = this.tplName
      document.body.append(a)
      a.click()
      document.body.removeChild(a)
    },
    onRemove() {
      this.fileList = [];
      this.isTxt = false;
    },
    onChange(file, fileList) {

      if (file.status === 'ready') {
        let message = '',
          { type, name } = file.raw

        if (this.supportTxt) {
          if (['txt'].indexOf(name.substr(name.lastIndexOf('.') + 1)) == -1) {
            message = '请上传txt格式'
          }
        } else {
          if (!(type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || ['xls', 'xlsx'].indexOf(name.substr(name.lastIndexOf('.') + 1)) !== -1)) {
            message = '请上传xls,xlsx格式'
          }
        }

        if ('txt'.indexOf(name.substr(name.lastIndexOf('.') + 1)) !== -1) {
          this.isTxt = true;
        }

        if (message) {
          this.$message({
            message,
            type: 'warning'
          });
          fileList.splice(0, fileList.length)
          this.fileList = []
          return false
        }

        fileList.splice(0, fileList.length - 1)
        this.fileList = [file]
      }
    },
    onError() {
      this.submitLoading = false
      this.$message({
        message: '上传失败',
        type: 'error'
      });
    },
    beforeUpload() {
      this.submitLoading = true
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-form {
  text-align: center;
}

.m-upload-file {
  ::v-deep.el-upload,
  ::v-deep.el-upload-list {
    width: 90%;
  }
  ::v-deep.el-upload-dragger {
    width: 100%;
  }
  ::v-deep.el-upload-list {
    text-align: left;
    margin: 0 auto;
  }
}
.upload-button-layout {
  text-align: center;
  margin-top: 10px;
}
.tipText {
  padding: 4px 0;
  color: red;
}
</style>
